import * as Cesium from "cesium";
import CesiumOverviewMapControl from "./CesiumOverviewMapControl";
import MeasureManager from "./MeasureManager";
import { mainStore } from "../store/index";
import { ElMessage, ElMessageBox } from "element-plus";
import EchartsLayer from "./Echartslayer";
import axios from "axios";
var viewer = null;
import map3D from "./3Dmap";
import Flat from "./flat";

var m_ServerInof = [];
// axios.get('http://125.46.5.250:2208/jc/config/config.json')
axios.get('/config/config.json')
    .then(res => {
        m_ServerInof = res.data[0];
        let mapurl = localStorage.getItem('mapurl');
        if (!mapurl) {
            localStorage.setItem('mapurl', m_ServerInof.m_3dmap.url);
        } else {

        }
    })
function f_SetMapViewer(v) {
    viewer = v;
}
/**获取当前相机信息 */
function f_GetCurCameraInfo() {
    return {
        heading: viewer.scene.camera.heading,
        pitch: viewer.scene.camera.pitch,
        roll: viewer.scene.camera.roll,
        lon: viewer.camera.position.x,
        lat: viewer.camera.position.y,
        height: viewer.camera.position.z,
    };
}
/**设置当前相机的信息 */
function f_SetMapView(heading, pitch, roll, lon, lat, height) {
    // console.log(heading, pitch, roll, lon, lat, height);
    if (heading) {
        viewer.camera.flyTo({
            destination: new Cesium.Cartesian3(lon, lat, height),
            orientation: {
                // 指向
                heading: heading,
                // 视角
                pitch: pitch,
                roll: roll,
            },
        });
    } else {
        viewer.camera.flyTo({
            //摄像机在 WGS84(世界)中的最终位置坐标或从自上而下的视图中可以看到的矩形
            destination: new Cesium.Cartesian3(
                viewer.camera.position.x,
                viewer.camera.position.y,
                viewer.camera.position.z
            ),
            //包含方向和向上属性或航向、俯仰和滚动属性的物体。默认情况下，方向将指向框架的中心在3D 和负 z 方向在哥伦布视图。
            //上行方向将指向当地北部的3D 和正 y 方向的哥伦布视图。在无限滚动模式下，2D 中不使用定位。
            orientation: {
                heading: Cesium.Math.toRadians(0),
                //   pitch: Cesium.Math.toRadians(-90),
                pitch: viewer.scene.camera.pitch,
                roll: 0.0,
            },
        });
    }
}
/**获取摄像机高度 */
function f_GetCameraHeight() {
    var cameraPos = viewer.camera.position;
    var ellipsoid = viewer.scene.globe.ellipsoid;
    var cartographic = ellipsoid.cartesianToCartographic(cameraPos);
    var height = cartographic.height;
    return height;
}
/**放大 */
function f_ZoomIn() {
    viewer.camera.zoomIn(f_GetCameraHeight() / 2);
}
/**缩小 */
function f_ZoomOut() {
    let hh = f_GetCameraHeight();
    if (hh < 1599999.0) {
        viewer.camera.zoomOut(f_GetCameraHeight() * 1.5);
    }
}
/**全图显示 */
function f_JZFullMap() {
    var obj =
    {
        heading: 6.2831853071795605,
        height: 3656111.4321642034,
        lat: 4800902.613922848,
        lon: -2050326.2213580548,
        pitch: -0.500110695236808,
        roll: 6.283185307179575
    }
    f_SetMapView( obj.heading, obj.pitch, obj.roll, obj.lon, obj.lat, obj.height);
}
/**
 * 清除实体
 */
function f_ClearEntities(type, code) {
    if (type) {
        for (var i = viewer.entities.values.length - 1; i >= 0; i--) {
            if (code) {
                if (
                    viewer.entities.values[i].type == type &&
                    Number(viewer.entities.values[i].code) == code
                ) {
                    viewer.entities.remove(viewer.entities.values[i]);
                }
            } else {
                if (viewer.entities.values[i].type == type) {
                    viewer.entities.remove(viewer.entities.values[i]);
                }
            }
        }
        if (code == 0 && braid) {
            braid.destroy(); //关闭事件句柄
            braid = null;
        }
    } else {
        for (var i = viewer.entities.values.length - 1; i >= 0; i--) {
            if (!viewer.entities.values[i].type) {
                viewer.entities.remove(viewer.entities.values[i]);
            }
        }
    }
}

/**
 * 清除3d模型
 */
function f_remove3Dtile() {
    console.log(m_3dtile, 'm_3dtile');
    viewer.scene.primitives.remove(
        m_3dtile
    );
}
/**
 * 测量距离 *
 * 左键开始测量,右键结束
 * */
function f_measureLine() {
    // f_ClearEntities();
    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
    );
    var m_cl_handler = new Cesium.ScreenSpaceEventHandler(
        viewer.scene._imageryLayerCollection
    );
    var positions = [];
    var poly = null;
    var distance = 0;
    var cartesian = null;
    var floatingPoint;
    var labelPt = null;
    m_cl_handler.setInputAction(function (movement) {
        let ray = viewer.camera.getPickRay(movement.endPosition);
        cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        if (!Cesium.defined(cartesian))
            //跳出地球时异常
            return;
        if (positions.length >= 2) {
            if (!Cesium.defined(poly)) {
                poly = new PolyLinePrimitive(positions);
            } else {
                positions.pop();
                positions.push(cartesian);
            }
        }
    }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

    m_cl_handler.setInputAction(function (movement) {
        let ray = viewer.camera.getPickRay(movement.position);
        cartesian = viewer.scene.globe.pick(ray, viewer.scene);
        if (!Cesium.defined(cartesian))
            //跳出地球时异常
            return;
        if (positions.length == 0) {
            positions.push(cartesian.clone());
        }
        positions.push(cartesian);
        //记录鼠标单击时的节点位置，异步计算贴地距离
        labelPt = positions[positions.length - 1];
        if (positions.length > 2) {
            getSpaceDistance(positions);
        } else if (positions.length == 2) {
            //在三维场景中添加Label
            //不能添加到viewer里面，不好清除掉
            floatingPoint = viewer.entities.add({
                name: "空间距离",
                position: labelPt,
                point: {
                    pixelSize: 5,
                    color: Cesium.Color.RED,
                    outlineColor: Cesium.Color.WHITE,
                    outlineWidth: 2,
                },
            });
        }
    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

    m_cl_handler.setInputAction(function (movement) {
        m_cl_handler.destroy(); //关闭事件句柄
        m_cl_handler = undefined;
        positions.pop(); //最后一个点无效
        if (positions.length == 1) viewer.entities.remove(floatingPoint);
    }, Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

    var PolyLinePrimitive = (function () {
        class _ {
            constructor(positions) {
                this.options = {
                    name: "直线",
                    polyline: {
                        show: true,
                        positions: [],
                        material: Cesium.Color.CHARTREUSE,
                        width: 3,
                        clampToGround: true,
                    },
                };
                this.positions = positions;
                this._init();
            }
            _init() {
                var _self = this;
                var _update = function () {
                    return _self.positions;
                };
                //实时更新polyline.positions
                this.options.polyline.positions = new Cesium.CallbackProperty(
                    _update,
                    false
                );
                viewer.entities.add(this.options);
            }
        }
        return _;
    })();

    //空间两点距离计算函数
    function getSpaceDistance(positions) {
        //只计算最后一截，与前面累加
        //因move和鼠标左击事件，最后两个点坐标重复
        var i = positions.length - 3;
        var point1cartographic = Cesium.Cartographic.fromCartesian(
            positions[i]
        );
        var point2cartographic = Cesium.Cartographic.fromCartesian(
            positions[i + 1]
        );
        getTerrainDistance(point1cartographic, point2cartographic);
    }

    function getTerrainDistance(point1cartographic, point2cartographic) {
        var geodesic = new Cesium.EllipsoidGeodesic();
        geodesic.setEndPoints(point1cartographic, point2cartographic);
        var s = geodesic.surfaceDistance;
        var cartoPts = [point1cartographic];
        for (var jj = 1000; jj < s; jj += 1000) {
            //分段采样计算距离
            var cartoPt = geodesic.interpolateUsingSurfaceDistance(jj);
            cartoPts.push(cartoPt);
        }
        cartoPts.push(point2cartographic);
        //返回两点之间的距离
        Cesium.sampleTerrain(viewer.terrainProvider, 8, cartoPts).then(
            (updatedPositions) => {
                for (var jj = 0; jj < updatedPositions.length - 1; jj++) {
                    var geoD = new Cesium.EllipsoidGeodesic();
                    geoD.setEndPoints(
                        updatedPositions[jj],
                        updatedPositions[jj + 1]
                    );
                    var innerS = geoD.surfaceDistance;
                    innerS = Math.sqrt(
                        Math.pow(innerS, 2) +
                        Math.pow(
                            updatedPositions[jj + 1].height -
                            updatedPositions[jj].height,
                            2
                        )
                    );
                    distance += innerS;
                }
                //在三维场景中添加Label
                var lon1 =
                    viewer.scene.globe.ellipsoid.cartesianToCartographic(
                        labelPt
                    ).longitude;
                var lat1 =
                    viewer.scene.globe.ellipsoid.cartesianToCartographic(
                        labelPt
                    ).latitude;
                var lonLat =
                    "(" +
                    Cesium.Math.toDegrees(lon1).toFixed(2) +
                    "," +
                    Cesium.Math.toDegrees(lat1).toFixed(2) +
                    ")";
                var textDisance = distance.toFixed(2) + "米";
                if (distance > 10000)
                    textDisance = (distance / 1000.0).toFixed(2) + "千米";
                floatingPoint = viewer.entities.add({
                    name: "贴地距离",
                    position: labelPt,
                    point: {
                        pixelSize: 5,
                        color: Cesium.Color.RED,
                        outlineColor: Cesium.Color.WHITE,
                        outlineWidth: 2,
                    },
                    label: {
                        text: textDisance,
                        font: "18px sans-serif",
                        fillColor: Cesium.Color.GOLD,
                        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                        outlineWidth: 2,
                        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                        pixelOffset: new Cesium.Cartesian2(20, -20),
                    },
                });
            }
        );
    }
}
/**测量面积 
 * 左键开始测量,右键结束
*/
function f_newmesure() {
    let m_MeasureManager = new MeasureManager(viewer);
    m_MeasureManager.measurePolygon();
}
/**
 * 定位
 * @param {number} x 经度
 * @param {number} y 纬度
 * @param {number} h 高度
 * @returns 
 */
function f_Zoomto(x, y, h) {
    viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(x, y, h),
    });
}
/**
 * 经纬度坐标转换为墨卡托坐标
 * @param {number} lon 经度
 * @param {number} lat 纬度
 * @returns 
 */
function f_lonlatToMercator(lon, lat) {
    var mercator = {};
    let x = lon * 20037508.34 / 180;
    let y = Math.log(Math.tan((90 + lat) * Math.PI / 360)) / (Math.PI / 180);
    y = y * 20037508.34 / 180;
    mercator.x = x;
    mercator.y = y;
    return mercator;
}
/**
 * 墨卡托坐标转换为经纬度坐标
 * @param {number} xx 
 * @param {number} yy 
 * @returns 
 */
function f_mercatorTolonlat(xx, yy) {
    let lonlat = {};
    let x = xx / 20037508.34 * 180;
    let y = yy / 20037508.34 * 180;
    y = 180 / Math.PI * (2 * Math.atan(Math.exp(y * Math.PI / 180)) - Math.PI / 2);
    lonlat.lon = x;
    lonlat.lat = y;
    return lonlat;
};
/**
 * 地图指北
 */
function f_Pointnorth() {
    viewer.camera.flyTo({
        //摄像机在 WGS84(世界)中的最终位置坐标或从自上而下的视图中可以看到的矩形
        destination: new Cesium.Cartesian3(
            viewer.camera.position.x,
            viewer.camera.position.y,
            viewer.camera.position.z
        ),
        //包含方向和向上属性或航向、俯仰和滚动属性的物体。默认情况下，方向将指向框架的中心在3D 和负 z 方向在哥伦布视图。
        //上行方向将指向当地北部的3D 和正 y 方向的哥伦布视图。在无限滚动模式下，2D 中不使用定位。
        orientation: {
            heading: Cesium.Math.toRadians(0),
            //   pitch: Cesium.Math.toRadians(-90),
            pitch: viewer.scene.camera.pitch,
            roll: 0.0,
        },
    });
}
function f_Init() {
    map3D.f_Msg();
}
/**
 * 自定义添加实体线
 * @param {string} name 线名称
 * @param {number} code 标识
 * @param {number} type 类型
 * @param {array<number>} geom 坐标数组
 * @param {number} width 宽度
 * @param {string} color 颜色
 */
function f_AddPolyCustom(name, code, type, geom, width, color) {
    var obj = viewer.entities.add({
        name: name,
        code: code,
        type: type,
        polyline: {
            positions: Cesium.Cartesian3.fromDegreesArray(geom),
            width: width,
            material: new Cesium.Color.fromCssColorString(color),
            clampToGround: true,
        },
    });
    viewer.zoomTo(obj);
}
/**
 * 添加面
 * @param {Array<number>} reg 面坐标
 */
function f_AddReg(reg) {
    f_ClearEntities();
    var stripeMaterial = new Cesium.StripeMaterialProperty({
        evenColor: Cesium.Color.WHITE.withAlpha(0.5),
        oddColor: Cesium.Color.BLUE.withAlpha(0.5),
        repeat: 5.0,
    });
    // var entities = viewer.entities;
    var obj = viewer.entities.add({
        polygon: {
            hierarchy: new Cesium.PolygonHierarchy(
                Cesium.Cartesian3.fromDegreesArray(reg)
            ),
            outline: true,
            outlineColor: Cesium.Color.WHITE,
            outlineWidth: 4,
            material: stripeMaterial,
        },
    });
    viewer.zoomTo(obj);
}
function f_LoadJson(url_json) {
    var geojsonOptions = {
        clampToGround: true, //使数据贴地
    };
    var promise = Cesium.GeoJsonDataSource.load(url_json, geojsonOptions);
    return promise;
}
function f_GetWGSXY(positionCartesian) {
    var positionWGS84 = viewer.scene.globe.ellipsoid.cartesianToCartographic(positionCartesian);
    var longitude = Cesium.Math.toDegrees(positionWGS84.longitude);
    var latitude = Cesium.Math.toDegrees(positionWGS84.latitude);
    var height = positionWGS84.height;
    return {
        x: longitude,
        y: latitude,
        z: height
    };
}

function f_crtSource() {
    var m_source = new Cesium.CustomDataSource("msource");
    return m_source;
}
var m_DWsourec = null;
/**
 * 添加单位
 * @param {string} name 单位名称
 * @param {number} id 标识
 * @param {number} type 类型
 * @param {string} url 图片地址
 * @param {Array<number>} xy 坐标
 */
function f_AddDanWei(
    name,
    id,
    type,
    url,
    xy,
    x,
    y
) {
    f_InitDanWei();
    // 注意对比: 路径参考我们的，最终路径要是'./xxx/xxxx.png',否则打包后路径找不到
    if (url) {
        var img = '.' + url;
    } else {
        var img = './img/sfzm.png';
        if (name.length <= 4) {
            img = './img/sfz.png';
        }
        else if (name.length > 4 && name.length <= 7) {
            img = './img/sfzl.png';
        }
    }

    // 注意对比:这里是点位写法，他们的标点函数不变就采用我们的格式写法
    m_DWsourec.entities.add({
        name: name,
        id: id,
        type: type,
        position: Cesium.Cartesian3.fromDegrees(xy[0], xy[1], 180),
        billboard: {
            image: img,
            pixelOffset: new Cesium.Cartesian2(0, 0),
            // pixelOffset: new Cesium.Cartesian2(-25, 20),
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            verticalOrigin: Cesium.VerticalOrigin.BASELINE,
            horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                0,
                150000
            ), //当缩放到一定程度时隐藏该实体,不设置则一直显示
        },
        label: {
            scale: 1,
            // text: name,
            text: '',
            font: `16px'微软雅黑'`,
            outlineWidth: 4.0,
            outlineColor: Cesium.Color.BLACK,
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            fillColor: Cesium.Color.fromCssColorString("#ffffff"),
            verticalOrigin: Cesium.VerticalOrigin.BASELINE,
            horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
            // pixelOffset: new Cesium.Cartesian2(40, -20),
            pixelOffset: new Cesium.Cartesian2(x || 15, y || 0),
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
                0,
                150000
            ), //当缩放到一定程度时隐藏该实体,不设置则一直显示
        },
    });
}

function f_InitDanWei() {
    if (!m_DWsourec) {
        m_DWsourec = f_crtSource();
        viewer.dataSources.add(m_DWsourec);
    } else {

    }
}
/**
 * 清除单位标注
 */
function f_ClearDanWei() {
    if (m_DWsourec) m_DWsourec.entities.removeAll();
}
var m_BianJieSource = null;

function f_AddBjLine() {
    if (!m_BianJieSource) {
        m_BianJieSource = new Cesium.CustomDataSource("mBianJieSource");
        viewer.dataSources.add(m_BianJieSource);
    }
    axios.get('./data/bj.json').then(res => {
        let features = res.data.features;
        const instances = [];
        for (let i = 0; i < features.length; i++) {
            for (let j = 0; j < features[i].geometry.coordinates.length; j++) {
                const polygonArray = features[i].geometry.coordinates[j].toString().split(',');
                for (let k = 0; k < polygonArray.length; k++) {
                    polygonArray[k] = Number(polygonArray[k]);
                }
                m_BianJieSource.entities.add({
                    type: "wall",
                    polyline: {
                        positions: Cesium.Cartesian3.fromDegreesArray(polygonArray),
                        clampToGround: true,
                        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                        material: Cesium.Color.DEEPSKYBLUE.withAlpha(0.4),
                        width: 4
                    },
                });
            }
        }
        console.log(m_BianJieSource, 'm_BianJieSource');
    });
    axios.get('./data/r_xianjie.json').then(res => {
        let features = res.data.features;
        const instances = [];
        for (let i = 0; i < features.length; i++) {
            for (let j = 0; j < features[i].geometry.coordinates.length; j++) {
                const polygonArray = features[i].geometry.coordinates[j].toString().split(',');
                for (let k = 0; k < polygonArray.length; k++) {
                    polygonArray[k] = Number(polygonArray[k]);
                }
                m_BianJieSource.entities.add({
                    type: "wall",
                    polyline: {
                        positions: Cesium.Cartesian3.fromDegreesArray(polygonArray),
                        clampToGround: true,
                        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                        material: Cesium.Color.GRAY.withAlpha(0.3),
                        width: 2
                    },
                });
            }
        }
    });

}
function f_ClearBjLine() {
    m_BianJieSource.entities.removeAll();
}
var m_arrDM = [];
function f_DrawDM() {
    m_arrDM = [];
    let shi = f_LoadJson("./data/p_shi.json");
    setTimeout(async () => {
        if (shi != null) {
            await shi.then(function (dataSource) {
                m_arrDM.push(dataSource);
                viewer.dataSources.add(dataSource);
                let entities = dataSource.entities.values;
                for (let i = 0; i < entities.length; i++) {
                    let entity = entities[i];
                    entity.billboard = null;
                    entity.label = {
                        scale: 1,
                        font: "20px '微软雅黑'",
                        outlineWidth: 3.0,
                        outlineColor: Cesium.Color.BLACK,
                        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                        verticalOrigin: Cesium.VerticalOrigin.BASELINE,
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                        pixelOffset: new Cesium.Cartesian2(0, -20),
                        text: entity.name,//图标名称
                        zIndex: 90,
                        fillColor: Cesium.Color.fromCssColorString("#ff0000"),
                        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                        //pixelOffset: new Cesium.Cartesian2(0, -30),
                        //scaleByDistance: new Cesium.NearFarScalar(1000, 1.8, 500000, 0.5),
                        distanceDisplayCondition:
                            new Cesium.DistanceDisplayCondition(
                                0,
                                500000
                            ),
                    }
                    //console.log(111,entity);
                }
            })

        }
    }, 0);
    let xian = f_LoadJson("./data/p_xian.json");
    setTimeout(async () => {
        if (xian != null) {
            await xian.then(function (dataSource) {
                m_arrDM.push(dataSource);
                viewer.dataSources.add(dataSource);
                let entities = dataSource.entities.values;
                for (let i = 0; i < entities.length; i++) {
                    let entity = entities[i];
                    entity.billboard = null;
                    entity.label = {
                        scale: 1,
                        font: "19px '微软雅黑'",
                        outlineWidth: 3.0,
                        outlineColor: Cesium.Color.BLACK,
                        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                        verticalOrigin: Cesium.VerticalOrigin.BASELINE,
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                        zIndex: 18,
                        text: entity.name,//图标名称
                        fillColor: Cesium.Color.fromCssColorString("#ff9205"),
                        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                        pixelOffset: new Cesium.Cartesian2(0, -19),
                        //scaleByDistance: new Cesium.NearFarScalar(1000, 2.0, 200000, 0.8),
                        distanceDisplayCondition:
                            new Cesium.DistanceDisplayCondition(
                                0,
                                500000
                            ),
                    }
                    //console.log(111,entity);
                }
            })

        }
    }, 0);
    let obj_gd = f_LoadJson("./data/p_xz.json");
    setTimeout(async () => {
        if (obj_gd != null) {
            await obj_gd.then(function (dataSource) {
                m_arrDM.push(dataSource);
                viewer.dataSources.add(dataSource);
                let entities = dataSource.entities.values;
                for (let i = 0; i < entities.length; i++) {
                    let entity = entities[i];
                    entity.billboard = null;
                    entity.label = {
                        scale: 1,
                        font: "16px '微软雅黑'",
                        outlineWidth: 3.0,
                        outlineColor: Cesium.Color.BLACK,
                        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                        verticalOrigin: Cesium.VerticalOrigin.BASELINE,
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                        text: entity.name,//图标名称
                        zIndex: 11,
                        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                        fillColor: Cesium.Color.DEEPSKYBLUE,
                        pixelOffset: new Cesium.Cartesian2(0, -10),
                        //scaleByDistance: new Cesium.NearFarScalar(50000, 1.2, 500000, 0.5),
                        distanceDisplayCondition:
                            new Cesium.DistanceDisplayCondition(
                                0,
                                100000
                            ),
                    }
                }
            })

        }
    }, 0);
    let obj_cun = f_LoadJson("./data/p_cun.json");
    setTimeout(async () => {
        if (obj_cun != null) {
            await obj_cun.then(function (dataSource) {
                m_arrDM.push(dataSource);
                viewer.dataSources.add(dataSource);
                let entities = dataSource.entities.values;
                for (let i = 0; i < entities.length; i++) {
                    let entity = entities[i];
                    entity.billboard = null;
                    entity.label = {
                        scale: 1,
                        font: "14px '微软雅黑'",
                        outlineWidth: 3.0,
                        outlineColor: Cesium.Color.BLACK,
                        style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                        verticalOrigin: Cesium.VerticalOrigin.BASELINE,
                        horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                        text: entity.name,//图标名称
                        zIndex: 11,
                        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                        fillColor: Cesium.Color.fromCssColorString("#ffff"),
                        pixelOffset: new Cesium.Cartesian2(0, -10),
                        //scaleByDistance: new Cesium.NearFarScalar(50000, 1.2, 500000, 0.5),
                        distanceDisplayCondition:
                            new Cesium.DistanceDisplayCondition(
                                0,
                                50000
                            ),
                    }
                }
            })

        }
    }, 0);
}
function f_clearDM() {
    m_arrDM.forEach((item, index) => {
        viewer.dataSources.remove(item);
    })
    m_arrDM = [];
}
var m_3dTileObj;
function f_Load3DTiles(id, url, height) {
    addThreeDTiles(id, url);
}
function f_Loadsingle3DTiles(id, url, height) {
    addThreeDTiles(id, url);

}
var m_3dtile;
async function addThreeDTiles(id, url, option) {
    viewer.scene.globe.depthTestAgainstTerrain = true;
    let tilesets = viewer.scene.primitives.add(
        new Cesium.Cesium3DTileset({
            // url: "http://125.46.5.250:9736/3d/dfd/tileset.json",
            url: url,
        })
    );
    tilesets.readyPromise.then(tileset => {
        var heightOffset = -200;
        var boundingSphere = tileset.boundingSphere;
        //获取3Dtlies的范围中心点的弧度
        var cartographic = Cesium.Cartographic.fromCartesian(boundingSphere.center);
        //定义3Dtlies改变之后中心点的弧度

        var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, cartographic.height);
        //模型改变的位置
        var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 65);

        //定义模型的改变状态
        var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
        tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);

    });
    // Red Hammer
    viewer.zoomTo(tilesets);
    m_3dtile = tilesets;
    return tilesets;
}


var m_arrMapXYMarker = [];
function f_AddXYZPOI(xy, hei) {
    var name = "经度:" + xy[0].toFixed(6) + "\n纬度:" + xy[1].toFixed(7) + "\n高度:" + hei.toFixed(0) + " 米";
    let POI = viewer.entities.add({
        position: Cesium.Cartesian3.fromDegrees(
            xy[0],
            xy[1],
            hei
        ),
        label: {
            text: name,
            font: "10pt '微软雅黑'",
            style: Cesium.LabelStyle.FILL_AND_OUTLINE,
            outlineWidth: 2,
            pixelOffset: new Cesium.Cartesian2(10, -10),
            verticalOrigin: Cesium.VerticalOrigin.BASELINE,
            outlineWidth: 2,
            fillColor: Cesium.Color.WHITE,
            outlineColor: Cesium.Color.BLACK,
            horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
            showBackground: true,
            strokeColor: Cesium.Color.WHITE,
            strokeWidth: 2,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            backgroundColor: Cesium.Color.fromCssColorString("#FF0000").withAlpha(0.6),
            distanceDisplayCondition:
                new Cesium.DistanceDisplayCondition(
                    0,
                    150000
                ),
        },
        billboard: {
            image: '/img/fx1.png',
            // width: 13,
            // height: 39,
            verticalOrigin: Cesium.VerticalOrigin.BASELINE,
            horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
            heightReference: Cesium.HeightReference.CLAMP_TO_GROUND, //贴地
            distanceDisplayCondition:
                new Cesium.DistanceDisplayCondition(
                    0,
                    150000
                ),
        }
    });
    m_arrMapXYMarker.push(POI);
}
function f_Load3DMapData() {
    f_remove3Dtile();
    // axios.get('http://125.46.5.250:2208/jc/config/config.json')
    axios.get('/config/config.json')
        .then(res => {
            m_ServerInof = res.data[0];
            let mapurl = localStorage.getItem('mapurl');
            if (!mapurl) {
                localStorage.setItem('mapurl', m_ServerInof.m_3dmap.url);
            } else {

            }
            f_Load3DTiles(m_ServerInof.m_3dmap.id, localStorage.getItem('mapurl'), m_ServerInof.m_3dmap.height);
        })
    // f_Loadsingle3DTiles(111,'/out/tileset.json',6)
}
/**
 * 切换3D模型的请求资源地址
 * @param {number} type 资源类型
 */
function f_set3Dmaptype(type) {
    if (type == 1 && m_ServerInof.m_3dmap.url != localStorage.getItem('mapurl')) {
        localStorage.setItem("mapurl", m_ServerInof.m_3dmap.url);
        // return;
    }
    if (type == 2 && m_ServerInof.m_3dmap.localurl != localStorage.getItem('mapurl')) {
        localStorage.setItem("mapurl", m_ServerInof.m_3dmap.localurl);
        // return;
    }
    // f_remove3Dtile();
    f_Load3DMapData();
}

function initwindow() {
    window.f_SetMapViewer = f_SetMapViewer
    window.f_GetCurCameraInfo = f_GetCurCameraInfo
    window.f_SetMapView = f_SetMapView
    window.f_Init = f_Init
    window.f_ZoomIn = f_ZoomIn
    window.f_ZoomOut = f_ZoomOut
    window.f_JZFullMap = f_JZFullMap
    window.f_ClearEntities = f_ClearEntities
    window.f_measureLine = f_measureLine
    window.f_newmesure = f_newmesure
    window.f_Zoomto = f_Zoomto
    window.f_lonlatToMercator = f_lonlatToMercator
    window.f_mercatorTolonlat = f_mercatorTolonlat
    window.f_Pointnorth = f_Pointnorth
    window.f_AddPolyCustom = f_AddPolyCustom
    window.f_AddReg = f_AddReg
    window.f_AddDanWei = f_AddDanWei
    window.f_ClearDanWei = f_ClearDanWei
    window.f_AddBjLine = f_AddBjLine
    window.f_ClearBjLine = f_ClearBjLine
    window.f_DrawDM = f_DrawDM
    window.f_clearDM = f_clearDM
}
//popup
function setPopupPos(location, popData) {
    mainStore().popshow = true;
    mainStore().popData = popData;
    // let cartesian = Cesium.Cartesian3.fromDegrees(Number(location[0]), Number(location[1]), 180)
    viewer.scene.postRender.addEventListener(() => {
        let windowPosition = Cesium.SceneTransforms.wgs84ToWindowCoordinates(viewer.scene, location);
        if (windowPosition) {
            mainStore().xAxis = windowPosition.x
            mainStore().yAxis = windowPosition.y
        }
    })
}
function clearPopup() {
    mainStore().popshow = false;
}
function f_SetLight(obj) {
    Cesium.knockout.track(obj);
    for (const name in obj) {

        if (obj.hasOwnProperty(name)) {
            Cesium.knockout
                .getObservable(obj, name)
                .subscribe(updatePostProcess);
        }
    }
    updatePostProcess(obj);
}
var handletype = 0;
function f_SetTool(type) {
    if (handletype == type && type == 1) {
        mainStore().geomShow = false;
        mainStore().geomInfo = '';
        ElMessage({
            message: '已取消坐标查询'
        })
        handletype = null;
        f_ClearEntities();
        // f_Load3DMapData();
    } else {
        mainStore().geomShow = true;
        // f_remove3Dtile();
        ElMessage({
            message: '点击地图查询坐标'
        })
        handletype = type;
    }
}
function f_eventCheck(lng, lat, movement) {
    if (handletype == 1) {
        mainStore().geomInfo = '经纬度:' + lng + ";" + lat + "; 高度:" + f_GetTerrainHeight(movement).toFixed(2) + "米;"
        f_AddXYZPOI([lng, lat], f_GetTerrainHeight(movement));
    }
}
function f_GetTerrainHeight(movement) {
    var ray = viewer.camera.getPickRay(movement.position);
    var cartesian1 = viewer.scene.globe.pick(ray, viewer.scene);
    var cartographic1 = Cesium.Cartographic.fromCartesian(cartesian1);
    var height = cartographic1.height;//的值为地形高度

    return height;
}
function updatePostProcess(obj) {
    const bloom = viewer.scene.postProcessStages.bloom;
    bloom.enabled = Boolean(obj.show);
    bloom.uniforms.glowOnly = Boolean(obj.glowOnly);
    bloom.uniforms.contrast = Number(obj.contrast);
    bloom.uniforms.brightness = Number(obj.brightness);
    bloom.uniforms.delta = Number(obj.delta);
    bloom.uniforms.sigma = Number(obj.sigma);
    bloom.uniforms.stepSize = Number(obj.stepSize);
}
function f_setView(x, y, h) {
    f_ClearEntities('temp')
    let height = h ? h : 200;
    var cartesian = Cesium.Cartesian3.fromDegrees(x, y, height);//经纬度坐标转Cartesian3
    var pointEntity = viewer.entities.add({
        position: cartesian,
        type: 'temp',
        point: {
            color: Cesium.Color.TRANSPARENT,
            pixelSize: 1,
        }
    });
    mainStore().popshow = true;//弹框展示
    viewer.scene.postRender.addEventListener(() => {
        var windowPosition = Cesium.SceneTransforms.wgs84ToWindowCoordinates(viewer.scene, Cesium.Cartesian3.fromDegrees(x, y));//Cartesian3转换为屏幕坐标
        if (windowPosition) {
            mainStore().xAxis = windowPosition.x//设置弹框位置为屏幕坐标x,y
            mainStore().yAxis = windowPosition.y
        }
    })
    viewer.flyTo(pointEntity, {
        offset: {
            heading: viewer.camera.heading,
            pitch: viewer.camera.pitch,
            roll: viewer.camera.roll
        },
    });
}

var pathdata = [[113.1098547228818, 35.21604123201404], [113.10999244674272, 35.21601430080428], [113.11012845021136, 35.2160204551285], [113.11027240285775, 35.21602187237588],
[113.11041252303085, 35.2160251467627], [113.1105599948718, 35.21603190493614], [113.11069389800248, 35.21603268074801], [113.11087051505092, 35.21603685848591],
[113.1110452597871, 35.216040928987546], [113.11128371583843, 35.21604494590831], [113.11148286769527, 35.21605328908108], [113.1116380365314, 35.216053266050615], [113.11186949484838, 35.21606172223249],
[113.11212329126492, 35.21606892786889], [113.1123293609541, 35.21607360673566], [113.11250909804482, 35.21607688917582], [113.11273237595718, 35.21607831858565]
    , [113.1127297447073, 35.21598398448071], [113.11272698985154, 35.21587107211949], [113.1127271913277, 35.21576606795657]
    , [113.11273245687454, 35.21563470416894], [113.1127316485407, 35.215512734354846], [113.11273255326016, 35.21538360862868]
    , [113.11273357370064, 35.21526629983263]];
var pathsource;
//路径回放
function f_pathRun() {
    pathsource = new Cesium.CustomDataSource('pathsource');
    viewer.dataSources.add(pathsource);
    pathsource.entities.add({
        name: 'pathline',
        polyline: {
            positions: Cesium.Cartesian3.fromDegreesArray(pathdata.flat()),
            material: Cesium.Color.RED,
            width: 1,

        }
    })
    var property = new Cesium.SampledPositionProperty();
    var starttime = new Date();
    var stoptime;
    var timestamp = starttime.getTime();
    pathdata.forEach((item, index) => {
        var time = new Date(timestamp + index * 3000);
        stoptime = time;
        var position = Cesium.Cartesian3.fromDegrees(item[0], item[1], 0)
        property.addSample(Cesium.JulianDate.fromDate(time), position)
    })
    property.setInterpolationOptions({
        interpolationDegree: 0.0001,
        interpolationAlgorithm: Cesium.LagrangePolynomialApproximation
    });
    var entitydd = pathsource.entities.add({
        availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
            start: Cesium.JulianDate.fromDate(starttime),
            stop: Cesium.JulianDate.fromDate(new Date(stoptime))
        })]),
        position: property,
        orientation: new Cesium.VelocityOrientationProperty(property),
        // billboard: {
        //     image: './img/pos.png',
        //     scale: 0.5,
        //     heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        //     clampToGround: true
        // },
        model: {
            uri: 'https://data.mars3d.cn/gltf/mars/man/walk.gltf',
            scale: 2,
            minimumPixelSize: 70,
            maximumScale: 70,
            clampToGround: true
        },
        path: {
            leadTime: 0,
            resolution: 1,
            material: new Cesium.PolylineGlowMaterialProperty({
                glowPower: 0.1,
                color: Cesium.Color.GREEN
            }),
            width: 10
        }
    });
    // viewer.clock.onTick.addEventListener((tick)=>{
    //     entitydd.position.getValue(tick.currentTime);
    //     var cartographic=Cesium.Ellipsoid.WGS84.cartesianToCartographic(entitydd.position.getValue(tick.currentTime))
    //     cartographic.longitude=Cesium.Math.toDegrees(cartographic.longitude)
    //     cartographic.latitude=Cesium.Math.toDegrees(cartographic.latitude)
    // })
    viewer.trackedEntity = entitydd;
    viewer.clock.currentTime = Cesium.JulianDate.fromDate(starttime).clone();
    viewer.clock.stopTime = Cesium.JulianDate.fromDate(new Date(stoptime)).clone();
    viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP;
    viewer.clock.shouldAnimate = true;
    // viewer.zoomTo(pathsource)
}
//路径回放-暂停
function f_pathPause() {
    viewer.clock.shouldAnimate = false; //暂停播放  
}
//路径回放-继续
function f_pathContinue() {
    viewer.clock.shouldAnimate = true;
}
//路径回放-取消
function f_pathcancel() {
    viewer.trackedEntity = null;
    // viewer.clock.currentTime = viewer.clock.startTime; 
    viewer.clock.shouldAnimate = false;
    // viewer.zoomTo(m_3dTileObj);
    viewer.dataSources.remove(pathsource)
    // f_JZFullMap()
}
function f_roadPoint() {
    axios.get('./data/lineroad.json').then(res => {
        createEchartsLayer(res.data)
    })
}
function createEchartsLayer(data) {
    const options = getEchartsOption(data)
    options.depthTest = false // 是否进行计算深度（大数据时，需要关闭）

    const echartsLayer = new EchartsLayer(viewer, options)


    // 图表自适应
    window.addEventListener("resize", function () {
        echartsLayer.resize()
    })
}
function getEchartsOption(data) {
    const option = {
        animation: false,
        visualMap: {
            type: "piecewise",
            left: "right",
            bottom: 46,
            min: 0,
            max: 15,
            splitNumber: 5,
            maxOpen: true,
            color: ["red", "yellow", "green"],
            textStyle: {
                color: "#ffffff"
            }
        },
        series: [
            {
                type: "lines",
                coordinateSystem: "cesiumContainer",
                polyline: true,
                data,
                lineStyle: {
                    normal: {
                        opacity: 1,
                        width: 4
                    },
                    emphasis: {
                        width: 6
                    }
                },
                effect: {
                    show: true,
                    symbolSize: 2,
                    color: "white"
                }
            }
        ]
    }
    return option;
}
export default {
    f_roadPoint,
    addThreeDTiles,
    f_Loadsingle3DTiles,
    f_pathPause,
    f_pathContinue,
    f_pathcancel,
    f_pathRun,
    f_setView,
    f_SetMapViewer,
    f_GetCurCameraInfo,
    f_SetMapView,
    f_Init,
    f_ZoomIn,
    f_ZoomOut,
    f_JZFullMap,
    f_ClearEntities,
    f_remove3Dtile,
    f_measureLine,
    f_newmesure,
    f_Zoomto,
    f_lonlatToMercator,
    f_mercatorTolonlat,
    f_Pointnorth,
    f_AddPolyCustom,
    f_AddReg,
    f_AddDanWei,
    f_ClearDanWei,
    f_AddBjLine,
    f_ClearBjLine,
    f_DrawDM,
    f_clearDM,
    f_set3Dmaptype,
    f_Load3DMapData,
    initwindow,
    setPopupPos,
    clearPopup,
    f_SetLight,
    f_AddXYZPOI,
    f_SetTool,
    handletype,
    f_eventCheck
}

